package com.zj.utils;

import com.zj.pojo.model.Goods;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * @author 赵赳
 * @since 2021/12/21 16:11
 */
public class HtmlParseUtils {

  public static void main(String[] args) throws Exception {
    parseJDGoodsData("Java").forEach(System.out::println);
    //var number = getNumber(11); //25825257
    //System.out.println("number = " + number);
  }


  public static List<Goods> parseJDGoodsData(String keyword) throws Exception {
    // https://search.jd.com/Search?keyword=java
    String url = "https://search.jd.com/Search?keyword=" + keyword;
    Document document = Jsoup.parse(new URL(url), 30000);
    //J_goodsList
    Element goodsList = document.getElementById("J_goodsList");
    Elements li = goodsList.getElementsByTag("li");
    List<Goods> list = new ArrayList<>();
    for (Element element : li) {
      Elements elements = element.getElementsByClass("p-img");
      Elements a = elements.get(0).getElementsByTag("a");
      // 图片
      var img = a.get(0).getElementsByTag("img").get(0).attr("data-lazy-img");

      var price = element.getElementsByClass("p-price").get(0).getElementsByTag("strong")
          .get(0).getElementsByTag("i").text();

      var title = element.getElementsByClass("p-name").get(0).getElementsByTag("a")
          .get(0).getElementsByTag("em").text();

      var goods = new Goods()
          .setId(getNumber(11))
          .setImg(img)
          .setPrice(Double.parseDouble(price))
          .setTitle(title);
      list.add(goods);
    }
    return list;
  }

  //随机数工具方法
  public static long getNumber(int length) {
    StringBuilder buf = new StringBuilder();
    Random random = new Random();
    /*开头不为0,建议数据量较少时只放开部分，比如1至3开头的数，等业务达到一定数量时，再逐步放开剩余的号码段，由于是固定位数，总数量一定，生成的数越多，重复的几率越大**/
    int firstNumber = random.nextInt(9) + 1;
    buf.append(firstNumber);

    for(int i = 0; i < length - 1; ++i) {
      buf.append(random.nextInt(10));
    }
    return Long.parseLong(buf.toString());
  }



}
